package kubernetes

import (
	"errors"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
	"k8s-admin/global"
	"k8s-admin/models"
	"time"
)

type InterfaceK8s interface {
	AddK8sCluster(cluster *models.Configs) (err error)
	ListK8sCluster(Limit, Page int) (*models.ClusterK8sList, error)
	ActiveK8sCluster(cid string) (cluster *models.Configs, err error)
	DeleteK8sCluster(cid []string) error
	ActiveK8sClusterList() (clusters []*models.Configs, err error)
	UpdateK8sCluster(cid string, status int) (err error)
}

type k8sCluster struct{}

func NewK8sCluster() InterfaceK8s {
	return &k8sCluster{}
}
func (k *k8sCluster) AddK8sCluster(cluster *models.Configs) (err error) {
	cluster.CreateBy = time.Now().Format(time.DateTime)
	if err = global.GORM.Model(&models.Configs{}).Create(&cluster).Error; err != nil {
		if mysqlErr, ok := err.(*mysql.MySQLError); ok {
			switch mysqlErr.Number {
			case 1062: // MySQL中表示重复条目的代码
				// 处理重复条目
				return errors.New("该集群已存在")
			// 为其他特定错误代码添加案例
			default:
				// 处理其他错误
				return err
			}
		} else {
			// 处理非MySQL错误或未知错误
			return nil
		}
	}
	return nil
}
func (k *k8sCluster) ListK8sCluster(Limit, Page int) (*models.ClusterK8sList, error) {
	var (
		K8sClusterList []*models.Configs
		total          int64
	)
	err := global.GORM.Model(&models.Configs{}).Find(&K8sClusterList).Count(&total).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("没有查询到对应集群数据")
		} else {
			return nil, err
		}
	} else {

		return &models.ClusterK8sList{
			Items: K8sClusterList,
			Total: total,
		}, nil
	}
}

func (k *k8sCluster) ActiveK8sCluster(cid string) (cluster *models.Configs, err error) {
	// 0表示在线
	err = global.GORM.Model(&models.Configs{}).Where("c_id = ? and status=?", cid, 0).Find(&cluster).Error
	if err != nil {
		return nil, err
	}
	return cluster, nil
}

func (k *k8sCluster) DeleteK8sCluster(cid []string) error {
	tx := global.GORM.Delete(&models.Configs{}, "c_id IN (?)", cid)
	if tx.RowsAffected == 0 {
		return errors.New("集群ID不存在")
	} else if tx.Error != nil {
		return tx.Error
	} else {
		return nil
	}
}

// 集群可用配置信息列表
func (k *k8sCluster) ActiveK8sClusterList() (clusters []*models.Configs, err error) {
	if err = global.GORM.Model(&models.Configs{}).Where("status = ?", 0).Find(&clusters).Error; err != nil {
		return nil, err
	}
	return clusters, nil
}

func (k *k8sCluster) UpdateK8sCluster(cid string, status int) (err error) {
	// 1表示不在线，0表示在线
	err = global.GORM.Model(&models.Configs{}).Where("c_id=?", cid).Update("status", status).Error
	if err != nil {
		return err

	} else {
		return nil
	}

}
